import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  Radio,
  message,
  Badge,
  Divider,
} from 'antd';
import { enquireScreen, unenquireScreen } from 'enquire-js';
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './TableList.less';

Date.prototype.Format = function (fmt) { //author: meizz
  var o = {
    "Y+": this.getUTCFullYear(),
    "M+": this.getMonth() + 1, //月份
    "D+": this.getDate(), //日
    "H+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
  if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
    
const statusMap = ['default','processing', 'success','error'];
const status = ['等待中', '发布中','成功','失败'];
// const mstatus = ['未用', '已用'];

const CreateForm = Form.create()(props => {
  const { modalVisible, form,article, handleAdd,accounts, handleModalVisible } = props;
  const okHandle = () => {
   
    form.validateFields((err, fieldsValue) => {
      fieldsValue.all_count = parseInt(fieldsValue.all_count)
      fieldsValue.less_count = fieldsValue.all_count 
      if (fieldsValue.all_count < 0){
          message.warn('发文数量不能小于0')
          return
      }
      if (fieldsValue.all_count > 99){
        message.warn('你怎么不发10000篇?!')
        return
      }
      if (fieldsValue.all_count > 999){
        message.warn('多读书,多看报,少发新闻,多睡觉.')
        return
      }
      if (err) return;
      form.resetFields();
      handleAdd(fieldsValue);
    });
  };

  const praseType = value => {
    switch(value){
      case 'BAIJIA':
        return "百家"
      case 'TOUTIAO':
        return "头条"
      case 'QIER':
        return "企鹅"
      case 'DAYU':
        return "大鱼"

    }
  }
 
  var listAccountsOption = () => {
    var res = [];
    for(var key in accounts){
      res.push(<Option key={key} value={accounts[key].id} >{praseType(accounts[key].plat)}-{accounts[key].nick_name}</Option>)
    }
    return res
  }

  var catsArray = {
    "娱乐":  "娱乐",
    "情感":  "情感",
    "社会":  "社会",
    "美食":  "美食",
    "国际":  "国际",
    "体育": "体育",
    "动漫":  "动漫",
		"财经":  "财经",
		"互联网": "互联网",
		"科技":  "科技",
		"汽车":  "汽车",
		"教育":  "教育",
		"时尚":  "时尚",
		"游戏":  "游戏",
		"旅游":  "旅游",
		"生活":  "生活",
		"创意":  "创意",
		"搞笑":  "搞笑",
		"美图":  "美图",
		"女人":  "女人",
		"家居":  "家居",
		"健康":  "健康",
		"两性":  "两性",
		"育儿":  "育儿",
		"文化":  "文化",
		"宠物":  "宠物",
		"科学":  "科学",
		"电影":  "电影",
  }

  var listOption = () => {
    var res = [];
    for(var key in catsArray){
      res.push(<Option key={key} value={key} >{key}</Option>)
    }
    return res
  }

  var handleChange = (e) => {
    // this.setState({ type: e.target.value });
  }


  return (
    <Modal
      title="新建自动发布任务:"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible(false)}
    >

       <FormItem labelCol={{ span: 7 }} wrapperCol={{ span: 15 }} label="账号">
        {form.getFieldDecorator('account_id',{
          rules: [{ required: true }],
        })
        ( <Select style={{ width: 180 }} onChange={this.handleChange}>
          {listAccountsOption()}
        </Select>)}
      </FormItem>

      <FormItem labelCol={{ span: 7 }} wrapperCol={{ span: 15 }} label="发文数量">
        {form.getFieldDecorator('all_count',{
          rules: [{ required: true }],
          initialValue: 10,
        })
        ( <Input style={{ width: 120 }} />)}
      </FormItem>

         <FormItem labelCol={{ span: 7 }} wrapperCol={{ span: 15 }} label="从该分类选择文章"
        >
          {form.getFieldDecorator('article_cat',{
          rules: [{ required: true }],
          initialValue: "kb_news_bagua",
        })(
          <Select style={{ width: 120 }} >
          <Option key="1" value="kb_news_hotnews" >热点</Option>
          <Option key="2" value="kb_news_bagua">娱乐</Option>
          <Option key="3" value="kb_news_sex">情感</Option>
          <Option key="4" value="kb_news_sports">运动</Option>
          <Option key="5" value="kb_news_laugh">搞笑</Option>
          <Option key="6" value="kb_news_tech">教育</Option>
          <Option key="7" value="kb_news_chaobao">时尚</Option>
          <Option key="8" value="kb_news_car">汽车</Option>
          <Option key="9" value="kb_news_beauty">美女</Option>
          <Option key="10" value="kb_news_nba">nba</Option>
          <Option key="11" value="kb_news_college">大学</Option>
          <Option key="12" value="kb_news_pet">宠物</Option>
          <Option key="13" value="kb_news_health">健康</Option>
          <Option key="14" value="kb_news_movie">电影</Option>
          <Option key="15" value="kb_news_baby">育儿</Option>
          <Option key="16" value="kb_news_gaojidi">数码</Option>
          <Option key="17" value="kb_news_cate">美食</Option>
        </Select>
          )}
        </FormItem>

      <FormItem labelCol={{ span: 7 }} wrapperCol={{ span: 15 }} label="发布分类">
        {form.getFieldDecorator('pub_cat',{
          rules: [{ required: true }],
          initialValue: "娱乐",
        })
        ( <Select style={{ width: 120 }} onChange={this.handleChange}>
          {listOption()}
      </Select>)}
      </FormItem>

    </Modal>
  );
});

let isMobile;
enquireScreen(b => {
  isMobile = b;
});

@connect(({ rule, loading }) => ({
  rule,
  loading: loading.models.rule,
}))
@Form.create()
export default class TableList extends PureComponent {
  state = {
    updateArticle:{},
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    type:"",
    isMobile:false,
  };

  componentDidMount() {
    this.enquireHandler = enquireScreen(mobile => {
      this.setState({
        isMobile: mobile,
      });
    });
    this.refresh()
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      page: pagination.current,
      size: pagination.pageSize,
      type: this.state.type,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'rule/autofetch',
      payload: params,
    });
  };


  refresh = () => {
    const { dispatch } = this.props;
    const { rule: { data:{ list, page,page_size }}} = this.props;
    
    dispatch({
      type: 'rule/autofetch',
      payload: {
        page:page,
        size:page_size,
        type:this.state.type,
      },
    });

    dispatch({
      type: 'rule/fetchPubAccounts',
    });
  }

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'rule/autofetch',
        payload: values,
      });
    });
  };



  renderForm() {
    return this.state.expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }
  handleChange = value => {
    console.log(`selected ${value}`);
    if (value == 'all'){
      this.state.type = ""
    } else{
      this.state.type = value
    }
    this.refresh()
  }

  useArticle = article => {
    this.props.dispatch({
      type: 'rule/updatePubStatus',
      payload: {
        article_id: article.article_id,
        status: article.status > 0? 0:1,
      },
      callback: () => {
        message.success('标记修改成功');
        this.refresh()
      }
    })
  }

  handleUpdateVisible = (flag,article) => {
    this.setState({
      updateArticle:article,
      modalVisible: !!flag,
    });
  }

  publish = (field) =>{
    this.props.dispatch({
      type: 'rule/addAutoTask',
      payload: field,
      callback: () => {
        this.refresh()
      }
    }),
    this.handleUpdateVisible(false)
  }
  
  praseType = value => {
    switch(value){
      case 'kb_news_bagua':
        return "娱乐"
      case 'kb_news_sports':
        return "运动"
      case 'kb_news_laugh':
        return "搞笑"
      case 'kb_news_hotnews':
        return "热文"
      case 'kb_news_sex':
        return '情感'
      case 'kb_news_tech':
        return '教育'
      case 'kb_news_chaobao':
        return '时尚'
      case 'kb_news_car':
        return '汽车'
      case 'kb_news_beauty':
        return '美女'
      case 'kb_news_nba':
        return 'nba'
      case 'kb_news_college':
        return '大鱼'
      case 'kb_news_pet':
        return '宠物'
      case 'kb_news_health':
        return '健康'
      case 'kb_news_movie':
        return '电影'
      case 'kb_news_baby':
        return '育儿'
      case 'kb_news_gaojidi':
        return '数码'
      case 'kb_news_cate':
        return '美食'
    }
  }
  
  praseDate = value => {
    var date = new Date(value)
    date.setHours(date.getHours()-8)
    var s = date.Format('YYYY-MM-DD HH:mm:ss')
    return s
  }


  prasePlat = value => {
    switch(value){
      case 'BAIJIA':
        return "百家"
      case 'TOUTIAO':
        return "头条"
      case 'QIER':
        return "企鹅"
      case 'DAYU':
        return "大鱼"
    }
  }

  render() {
    // praseType = this.praseType
    const { rule: { autoTasks,pubAccounts }, loading } = this.props;
    const { selectedRows, modalVisible,updateArticle } = this.state;
    var columns = []
    if (isMobile){
      columns = [
        {
          title: 'Id',
          dataIndex: 'id',
          render: val => <span>{val}</span>,      
        },          
        {
          title: '用户',
          render: (val,record) => <span>{"["+this.prasePlat(record.account.plat)+"]"+record.account.nick_name}</span>,
        },
        {
          title: '分类',
          width: 50,
          dataIndex: 'article_cat',
          render: val => <span>{this.praseType(val)}</span>,
        },
        {
          title: '总数',
          width: 50,
          dataIndex: 'all_count',
          render: val => <span>{val}</span>,
        },
        {
          title: '已发',
          width: 50,
          dataIndex: 'less_count',
          render: (val,record) => <span>{record.all_count-record.less_count}</span>,
        },
        {
          title: '状态',
          width: 60,
          dataIndex: 'status',
          render(val) {
            return <Badge status={statusMap[val]} text={status[val]} />;
          },
        },
      ];
    }else{
      columns = [
      {
        title: 'Id',
        dataIndex: 'id',
        render: val => <span>{val}</span>,      
      },
      {
        title: '用户',
        render: (val,record) => <span>{record.account.nick_name}</span>,      
      },
      {
        title: '平台',
        render: (val,record) => <span>{this.prasePlat(record.account.plat)}</span>,      
      },
      {
        title: '分类',
        dataIndex: 'article_cat',
        render: val => <span>{this.praseType(val)}</span>,
      },
      {
        title: '总数',
        dataIndex: 'all_count',
        render: val => <span>{val}</span>,
      },
      {
        title: '已发',
        dataIndex: 'less_count',
        render: (val,record) => <span>{record.all_count-record.less_count}</span>,
      },
      {
        title: '状态',
        dataIndex: 'status',
        render(val) {
          return <Badge status={statusMap[val]} text={status[val]} />;
        },
      },
      {
        title: '时间',
        dataIndex: 'create_time',
        render: val => <span>{this.praseDate(val)}</span>,
      }]
    }

    const parentMethods = {
      handleAdd: this.publish,
      handleModalVisible: this.handleUpdateVisible,
      article: updateArticle,
      accounts:pubAccounts,
    };

    return (
      <div style={{ margin: '0 -46px 0' }}>
        <Card className={styles.card} bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListOperator}>
              <Button style={{ marginRight: 10}} type="primary" onClick={() => this.refresh()}>
                刷新
              </Button>
              <Button style={{ marginRight: 10}} icon="plus" type="primary" onClick={() => this.handleUpdateVisible(true)}>
                新建
              </Button>
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={autoTasks}
              pagination={true}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
            </div>
        </Card>
        <CreateForm {...parentMethods} modalVisible={modalVisible} />
      </div>
    );
  }
}
